import {Component} from 'react';
import PropTypes from "prop-types";
import "./index.scss"
import {nanoid} from "nanoid";

export default class Header extends Component {
  static propTypes = {
    addTodo: PropTypes.func.isRequired
  }

  // 按回车添加数据
  handleAdd = (event) => {
    const {keyCode, target} = event
    // 判断是不是回车键
    if (keyCode === 13) {
      // 判断输入是否为空
      if (target.value.trim() === '') return alert('输入不能为空')
      // 添加新对象
      const newItem = {id: nanoid(), name: target.value, done: false}
      // 调父的方法，将新的todo加入列表
      this.props.addTodo(newItem)
      // 清空输入框
      target.value = ''
    }
  }

  render() {
    return (
      <div className="todo-header">
        <input type="text" placeholder="请输入待办任务，回车添加" onKeyUp={this.handleAdd}/>
      </div>
    );
  }
}
